from rest_framework import serializers
from django_redis import get_redis_connection
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from django.conf import settings
from .models import OAuthQQUser
from rest_framework_jwt.settings import api_settings

# 定义绑定数据的序列化模型类
from user.models import User


class QQAuthUserSerialize(serializers.Serializer):
    mobile = serializers.RegexField(regex='^1[3-9]\d{9}$', label='手机号码', write_only=True)
    password = serializers.CharField(label='密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    access_token = serializers.CharField(label='操作凭证', write_only=True)
    token = serializers.CharField(read_only=True)
    username = serializers.CharField(read_only=True)
    id = serializers.IntegerField(read_only=True)

    # 验证
    def validate(self, attrs):
        # attrs 有序字典
        # redis数据库连接
        conn = get_redis_connection('verify')
        # 判断验证码是否正确
        if attrs['sms_code'] != conn.get('sms_code_%s'%attrs['mobile']).decode():
            raise serializers.ValidationError({"message":"验证码错误"})
        #　判断access_token是否正确
        # 获取身份凭证
        tjs = TJS(settings.SECRET_KEY, 300)
        try:
            data = tjs.loads(attrs['access_token'])
        except:
            raise serializers.ValidationError('错误的access_token')
        openid = data.get('openid')
        if not openid:
            raise serializers.ValidationError('openid失效')
        attrs['openid'] = openid

        # 验证该号码是否已注册
        try:
            user = User.objects.get(mobile=attrs['mobile'])
        except:
            return attrs
        if user.check_password(attrs['password']):
            attrs['user'] = user
            return attrs
        raise serializers.ValidationError({'message':'密码错误'})

    # 定义创建函数
    def create(self, validated_data):
        # validated_data 字典
        user = validated_data.get('user', None)
        if not user:
            # 注册该用户
            user = User.objects.create_user(username=validated_data['mobile'], mobile=validated_data['mobile'], password=validated_data['password'])
        # 绑定用户
        OAuthQQUser.objects.create(openid=validated_data['openid'], user=user)

        # 设置jwt token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return user








